package com.wj.graph;

import com.wj.linear.Queue;
import com.wj.linear.Stack;

/**
 * @author wen.jie
 * @date 2021/8/27 14:52
 */
public class BreadthFirstPaths {

    //索引代表顶点，值代表当前顶点是否已经被搜索
    private boolean[] marked;
    //用来存储待搜索邻接表的点
    private Queue<Integer> waitSearch;
    //索引代表顶点，值代表从起点s到当前顶点路径上的最后一个顶点
    private Integer[] edgeTo;

    public BreadthFirstPaths(Graph G, int s) {
        this.marked = new boolean[G.V()];
        this.waitSearch = new Queue<>();
        this.edgeTo = new Integer[G.V()];
        bfs(G, s);
    }

    //深度优先搜索找出G图中v顶点的所有相通顶点
    private void bfs(Graph G, int v) {
        //标记起点
        marked[v] = true;
        //入队列,待搜索
        waitSearch.enqueue(v);
        while (!waitSearch.isEmpty()) {
            //出队列
            Integer wait = waitSearch.dequeue();
            for (Integer w : G.adj(wait)) {
                if (!marked[w]) { //对于每个未被标记的相邻顶点
                    edgeTo[w] = wait; //保存最短路径的最后一条边
                    marked[w] = true; //标记，因为最短路径已知
                    waitSearch.enqueue(w); //入队列
                }
            }
        }

    }

    //判断w顶点与s顶点是否相通
    public boolean hasPathTo(int w){
        return marked[w];
    }

    //找出从起点s到顶点v的路径(就是该路径经过的顶点)
    public Stack<Integer> pathTo(int v){

        if (!hasPathTo(v))
            return null;
        Stack<Integer> path = new Stack<>();
        path.push(v);
        while (edgeTo[v] != null) {
            int p = edgeTo[v];
            path.push(p);
            v = p;
        }
        return path;
    }
}
